package com.one.consumer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.one.bean.OrderInfo;
import com.one.bean.Orders;
import com.one.constant.RabbitMQConstant;
import com.one.mapper.OrderInfoMapper;
import com.one.mapper.OrderMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Create on 2022-01-19
 * <p>
 * Author: LiangWei
 * <p>
 * Description: 监听死信队列
 **/
@Slf4j
@Component
public class RabbitMQDlxConsumer {
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderMapper orderMapper;
    @RabbitListener(queues = {RabbitMQConstant.RABBITMQ_DIRECT_DLX_QUEUE})
    public void consumerDlxMsgFromDlxQueue(Map directMap,Message message, Channel channel) throws Exception {
        //获取消息的唯一标识，消费者向rabbitMQ注册时，自动创建一个通道channel，rabbitmq向消费者，推送消息。每个消息都会自动携带一个唯一标识（仅限于当前通道递增的正整数）
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
       try{
           String orderNo = (String) directMap.get("OrderNo");
           //根据订单号查询订单
           QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
           wrapper.eq("order_no",orderNo);
           OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);
           //如果订单是待支付状态，则改为取消订单状态
           if(orderInfo.getStatus()==1){
               orderInfo.setStatus(0);
               orderInfoMapper.updateById(orderInfo);
               QueryWrapper<Orders> wrapper1 = new QueryWrapper<>();
               wrapper1.eq("order_no",orderNo);
               List<Orders> orders = orderMapper.selectList(wrapper1);
               for(int i=0;i<orders.size();i++){
                   Orders orders1 = orders.get(i);
                   orders1.setStatus(0);
                   orderMapper.updateById(orders1);
               }
           }
           channel.basicAck(deliveryTag,false);
       }catch (Exception e){
           channel.basicReject(deliveryTag,false);
       }
    }
}
